package cn.pugle.oj.leetcode;

import cn.pugle.oj.catalog.TreeProblem;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * 中序遍历树, 非递归
 *
 * @author tzp
 * @since 2020/10/12
 */
public class LC94_1 implements TreeProblem {
    /**
     * see {@link cn.pugle.oj.base.TreeTravel#dfsMid1(TreeNode)} )
     */
    public List<Integer> inorderTraversal(TreeNode root) {
        if (root == null) return Collections.emptyList();
        List<Integer> result = new ArrayList<>();

        LinkedList<TreeNode> linkedList1 = new LinkedList<>();
        LinkedList<TreeNode> linkedList2 = new LinkedList<>();
        linkedList1.addLast(root);
        while (linkedList1.size() != 0 || linkedList2.size() != 0) {
            TreeNode cur = linkedList1.pollLast();
            if (cur != null) {
                if (cur.left != null) {
                    linkedList2.addLast(cur);
                    linkedList1.addLast(cur.left);
                } else {
                    result.add(cur.val);
                    if (cur.right != null) linkedList1.addLast(cur.right);
                }
            } else {
                cur = linkedList2.pollLast();
                result.add(cur.val);
                if (cur.right != null) linkedList1.addLast(cur.right);
            }
        }
        return result;
    }


    public static void main(String[] args) {
        Integer[] a = {1, 2, 4, 3, 5, 7, 10, 6, null, 8, null, 11, 9, 15, null, null, null, 12, null, null, null, 13, null, null, null, null, 14};
        //[6, 3, 2, 12, 14, 8, 5, 1, 11, 7, 13, 9, 4, 15, 10]
        TreeNode treeNode = TreeNode.arrayToTreeNode(a);
        System.out.println(new LC94_1().inorderTraversal(treeNode));
    }
}
